<template class="">
  <el-container id="question" class="text-32">
    <el-aside ref="aside" :width="asidewidth" class="container-content">
      <el-tabs stretch type="border-card" v-model="activeName" @tab-change="tabChange">
        <el-scrollbar>
          <!-- 题目详情 -->
          <el-tab-pane lazy :name="Tabs.QUESTIONDETAIL" label="题目详情" class="tab-container">
            <Questioncontext :question="question" :routerNames="routerNames"></Questioncontext>
          </el-tab-pane>
          <!-- 我的提交 -->
          <el-tab-pane lazy :name="Tabs.MYSUBMISSION" label="" class="tab-container">
            <template #label>
              <el-badge :value="submissionCount" :offset="[6, 0]" type="primary" :hidden="hiddenBadge">
                <span>我的提交{{ hiddenBadge ? `(${submissionCount})` : '' }}</span>
                <!-- <template #content>
                  <MynumberVue :num="submissionCount"></MynumberVue>
                </template> -->
              </el-badge>
            </template>
            <SubmissionTable ref="submissionTable" :user="getuser" :isSub="isSub" :ID="ID" :question="question"
              :questionbank="Number(questionbankid)" @update:submissionRow="updateSubmissionRow"
              @update:showCaseDetail="updateShowCaseDetail">
            </SubmissionTable>
          </el-tab-pane>
          <!-- 题目讨论 屏蔽:因为数据没有区分团队 -->
          <el-tab-pane lazy v-if="false && routerNames.find(e => e === '题目讨论')" :name="Tabs.QUESTIONDISCUSS" label=""
            class="tab-container">
            <template #label>
              <el-badge :value="discussCount" :offset="[6, 0]" type="primary" :hidden="hiddenBadge">
                <span>题目讨论{{ hiddenBadge ? `(${discussCount})` : '' }}</span>
                <!-- <template #content>
                  <MynumberVue :num="discussCount"></MynumberVue>
                </template> -->
              </el-badge>
            </template>
            <QuestionDiscuss :user="getuser" :isSub="isSub" :ID="ID" :question="question"> </QuestionDiscuss>
          </el-tab-pane>
          <!-- 题目题解-->
          <el-tab-pane lazy v-if="showUserSolution" :name="Tabs.QUESTIONSOLUTION" label="" class="tab-container">
            <template #label>
              <el-badge :value="solutionCount" :offset="[6, 0]" type="primary" :hidden="hiddenBadge">
                <span>题目题解{{ hiddenBadge ? `(${solutionCount})` : '' }}</span>
                <!-- <template #content>
                  <MynumberVue :num="solutionCount"></MynumberVue>
                </template> -->
              </el-badge>
            </template>
            <UserSolution :user="getuser" :isSub="isSub" :ID="ID" :question="question"> </UserSolution>
          </el-tab-pane>
          <!-- 思路提示 -->
          <el-tab-pane lazy v-if="showIdeaTips || isHGKJteam" :name="Tabs.AIIDEATIPS" label="" class="tab-container">
            <template #label>
              <el-badge :value="ideaTipsCount" :offset="[6, 0]" type="primary" :hidden="hiddenBadge">
                <span>思路提示{{ hiddenBadge ? `(${ideaTipsCount ? 1 : 0})` : '' }}</span>
                <!-- <template #content>
                  <MynumberVue :num="ideaTipsCount"></MynumberVue>
                </template> -->
              </el-badge>
            </template>
            <AIIdeaTips :user="getuser" :ID="ID" :question="question"> </AIIdeaTips>
          </el-tab-pane>
          <!-- 分页 -->
          <el-tab-pane lazy disabled :name="Tabs.PAGER" class="tab-container">
            <template #label>
              <div class="foter">
                <div v-if="showChgPageBtn" class="question-chg-page-btn-box">
                  <el-button class="question-chg-page-btn" type="primary" plain size="default"
                    @click.stop="goNext(true)" :disabled="des === 'T'">
                    <el-icon>
                      <ArrowLeft />
                    </el-icon>
                    上一题
                  </el-button>
                  <span>
                    &nbsp; {{questionlist.findIndex((v) => v?.ID == ID) + 1}} /
                    {{ questionlist.length }} &nbsp;
                  </span>
                  <el-button class="question-chg-page-btn" type="primary" plain size="default"
                    @click.stop="goNext(false)" :disabled="des === 'F'">
                    下一题
                    <el-icon>
                      <ArrowRight />
                    </el-icon>
                  </el-button>
                </div>
                <el-button class="question-question-list-btn" type="primary" plain size="default"
                  @click.stop="listshow = !listshow">
                  <svg class="icon" aria-hidden="true">
                    <use xlink:href="#icon-Menu" />
                  </svg>
                  &nbsp; 题目列表
                </el-button>
              </div>
            </template>
            <Questioncontext :question="question" :routerNames="routerNames"></Questioncontext>
          </el-tab-pane>
        </el-scrollbar>

      </el-tabs>
      <!-- 题目列表 -->
      <el-drawer size="650px" class="eldrawer" title="题目列表" direction="ltr" v-model="listshow" :with-header="false">
        <Questionlist v-show="listshow" :change="changePage" :questions="questionlist"
          :getquestioncount="getquestioncount" :questionbankid="questionbankid" :limit="limit" :offset="offset"
          :order="order" :ID="ID" @update:listshow="hiddenList" :CFID="route.query.range === 'codeforces'">
        </Questionlist>
      </el-drawer>
    </el-aside>
    <el-main :class="['position-relative p-0 container-right-box', showCaseDetail ? 'container-box-shadow' : '']">
      <!--   -->
      <div class="zrleft" ref="zrleft"></div>
      <!-- 测试点详情 -->
      <div v-if="showCaseDetail" ref="showCaseDetailEl" class="submission-container-right">
        <el-scrollbar>
          <Submission :submissionRow="submissionRow" :user="getuser" :isSub="isSub" :ID="ID" :question="question"
            @update:editerContent="updateEditerContent" @update:showCaseDetail="updateShowCaseDetail"
            :questionbank="Number(questionbankid)">
          </Submission>
        </el-scrollbar>
      </div>
      <!-- 编辑器 -->
      <div v-else class="monaco-container-box">
        <div ref="monacoEl" :style="{ height: monacoHeight }" class="monaco-container container-right">
          <div class="monaco-header">
            <div class="headers" v-if="question.range === 'codeforces'">
              <el-select size="default" :style="{ width: '300px', display: 'inline-block' }" v-model="language2"
                placeholder="请选择">
                <el-option v-for="(item, k) in codeforcesLanguage" :label="item.name" :value="item.value" :key="k">
                  {{ item.name }}
                </el-option>
              </el-select>
            </div>
            <div v-else class="headers">
              <el-select size="default" :style="{ width: '100px', height: '32px', display: 'inline-block' }"
                v-model="language1" placeholder="请选择">
                <el-option label="C" value="C">C</el-option>
                <el-option label="C++" value="C++">C++</el-option>
                <el-option label="Python" value="Python">Python</el-option>
              </el-select>
              <span v-if="['C++', 'C', 'CPP'].includes(language1)">
                &nbsp; <el-checkbox v-model="gccoptimize">O2优化</el-checkbox>
              </span>
              <span>
                &nbsp; <el-checkbox size="default" v-model="isfile">文件读写</el-checkbox>
              </span>
              <span style="height: 32px;line-height: 32px;display: inline-block;" :title="languages[language1].title">
                &nbsp; 编译环境: {{ languages[language1].text }}
              </span>
            </div>
            <div style="display: flex;  
              align-items: center;    justify-content: center;">
              <el-button v-if="contextLength && (codeHelp || isHGKJteam)" type="" plain class="code-AI-btn">
                <AICodeHelpDialog :user="getuser" :ID="ID" :question="question" :context="context" :language="language">
                </AICodeHelpDialog>
              </el-button>
              <el-button size="default" class="code-submit-btn" type="primary" :loading="loading"
                @click="runcode(true)">
                <el-icon v-show="!loading">
                  <UploadFilled />
                </el-icon>&nbsp;
                <!-- <span class="emoji">🙏</span> -->
                提交代码
              </el-button>
            </div>
          </div>
          <!-- 编辑器 -->
          <MonaoEditor id="monaco" ref="editor" :value="context" @change="change"
            v-bind="{ language, language2, options: { minimap: { enabled: false, }, }, }">
          </MonaoEditor>
        </div>
        <!-- 改变高度的滑动条 -->
        <div class="zrUp" v-if="!isCf" ref="zrUp"></div>
        <!-- 控制台 -->
        <ConsoleQuestion v-show="!isCf" class="console-question" :class="{ 'transition-enabled': isTransitionEnabled }"
          :style="{ height: consoleHeight }" ref="consoleQuestionRef" v-model:textarea="textarea"
          v-bind="{ ouput, drawer, runcode, range: question.range, loading: runTestLoading, question }">
        </ConsoleQuestion>
      </div>
      <!-- </el-scrollbar> -->
    </el-main>
    <!-- AI聊天 -->
    <AIChatDialog :user="getuser" :contextDataString="chatContextString" v-if="showAIChat" />
  </el-container>
</template>

<script setup lang='ts'>
import { useElementBounding, useMouse, useMousePressed } from "@vueuse/core";
import { ElMessage, TabPaneName } from "element-plus";
import * as monaco from "monaco-editor";
import { Socket } from "socket.io-client";
import { computed, ComputedRef, inject, onMounted, reactive, ref, watch } from "vue";
import { onBeforeRouteLeave, useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asyncgetfabulouscomment, asyncselectuserquestion, asyncselectusersolution, asyncUserSelectacaicontent, Iobj, jilurizhi, selectteamrole } from "../../../api";
import AIChatDialog from "../../../components/AIChat/AIChatDialog.vue"; // 新增导入，注意路径
import MonaoEditor from "../../../components/MonaoEditor.vue";
import { Ilang, Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { codeforcesLanguage } from "../../../util/codeforces";
import { adminTeamId } from "../../../util/data";
import { dealy } from "../../../util/time";
import ConsoleQuestion from "../../components/watchQuestion/ConsoleQuestion.vue";
import { languages } from '../../data/data';
import AIIdeaTips from "./AIIdeaTips.vue";
import Submission from './Submission.vue';
import SubmissionTable from './SubmissionTable.vue';
import AICodeHelpDialog from "./components/AICodeHelpDialog.vue";
import Questioncontext from './context.vue';
import QuestionDiscuss from "./discuss.vue";
import Questionlist from "./questionlist.vue";
import UserSolution from "./usersolution.vue";

const contextLimit = 20
const enum Tabs {
  QUESTIONDETAIL = "questionDetail",
  MYSUBMISSION = "mySubmission",
  QUESTIONDISCUSS = "questionDiscuss",
  QUESTIONSOLUTION = "questionSolution",
  // AI 思路提示
  AIIDEATIPS = "AIIdeaTips",
  PAGER = "pager"
}

const prop = defineProps<{ ID: number, question: Studycodemodel.Iquestion, questionlist: Studycodemodel.Iquestion[] }>()
const ID = computed(() => {
  return prop.ID;
});

const router = useRouter();
const route = useRoute();
const store = useStore(Storekey);
const getuser = computed<Studycodemodel.Iuser>(() => {
  return store.getters.getuser;
});
const teamId = computed(() => {
  return getuser.value?.teamid
})
const isAdmin = computed(() => {
  return getuser.value?.isAdmin
})
const getteam = computed(() => {
  return store.state.team?.rows || []
})
// isHGKJteam
const isHGKJteam = computed(() => { return getuser?.value.teamid === adminTeamId })
const showIdeaTips = computed(() => { return getteam.value.some(c => c?.other?.ideaTips) })
const codeHelp = computed(() => { return getteam.value.some(c => c?.other?.codeHelp) })
const contextLength = computed(() => { return prop.question?.context?.length || 0 >= contextLimit })

// 获取权限
const roleName = "学生"
const routerNames = ref<any[]>([])
async function getPermissionsCfg() {
  const { count, rows } = await selectteamrole({
    teamid: teamId.value, name: roleName
  })
  // 可能存在多条
  routerNames.value = rows[0]?.routername || []
}

const getquestioncount = computed<number>(() => {
  // 专题是单独获取的题目列表
  if (questionbankid.value || userId.value) {
    return questionlist.value.length
  }
  // 题库、比赛、任务
  return store.getters.getquestioncount;
});
const questionbankid = computed(() => {
  return route.query.questionbankid as string | number | undefined;
});
const userId = computed(() => {
  return route.query.userId;
});
const getquestion = computed<Studycodemodel.Iquestion[]>(() => {
  return store.getters.getquestion;
});
const getMyPractiseQuestion = computed(() => {
  return store.getters.getMyPractiseQuestion;
});
const questionlist = computed(() => {
  return prop.questionlist
  if (questionbankid.value) {
    const x = prop.question.questionquestionbank?.map((v) => {
      if (v.question) {
        return v.question
      }
      return {}
    });
    return x || [];
  } else if (userId.value) {
    return getMyPractiseQuestion.value
  }
  return getquestion.value;
});

const codeforcesref = ref()
const _runcode = inject("runcode", () => true);

// tabs-name
const activeName = ref<Tabs>(Tabs.QUESTIONDETAIL)
const showCaseDetail = ref(false)
function updateShowCaseDetail(isShow: boolean) {
  showCaseDetail.value = isShow
}
const submissionRow = ref({})
// 更新传入 submission 的 submissionRow
function updateSubmissionRow(row: Studycodemodel.Iuserquestion) {
  submissionRow.value = row || {};
}
const submissionTable = ref(null)
// tab切换至题目详情时
function tabChange(name: TabPaneName) {
  if (name === Tabs.QUESTIONDETAIL) {
    // 右侧隐藏、数据清空
    showCaseDetail.value = false
    submissionRow.value = {};
    // 我的提交列表选中数据清空
    submissionTable.value?.defaultSelectedRow({})
  }
}
// 
function updateEditerContent(v: string) {
  context.value = v
}

const consoleQuestionRef = ref();

const drawer = ref(true); // 默认开启控制台
const listshow = ref(false);
function hiddenList(v: boolean) {
  listshow.value = v;
}
const textarea = ref("");
const language = ref<Ilang>("CPP");
const language1 = computed({
  get() {
    if (language.value === "CPP") {
      return "C++";
    }
    return language.value;
  },
  set(e: Ilang) {
    if (e === "C++") {
      language.value = "CPP";
    } else {
      language.value = e;
    }
  },
});

const gccoptimize = ref<boolean>(true)
const isfile = ref<boolean>(false)

const language2 = ref(54)
const context = ref("");
const loading = ref(false);
// 运行测试 loading
const runTestLoading = ref(false);
const isSub = ref(false);
const ouput = reactive<Studycodemodel.Iuserquestioninfo>({
  t: 0,
  stdout: "",
  stderr: "",
});
const getcode = inject<ComputedRef<{
  data?: Studycodemodel.Iuserquestioninfo[];
  run?: true;
  error?: number;
  msg?: string;
}>
>("getcode");

// 
const showChgPageBtn = computed(() => {
  return !!(route.query.jobid || route.query.activityid || questionbankid.value)
})
// 
const des = computed<false | "T" | "F">(() => {
  const currQuestionIdx = questionlist.value.findIndex((v) => v?.ID == ID.value);
  // 上一题不可点击
  if (currQuestionIdx === 0 && offset.value == 0) {
    return "T";
  }
  // 下一题不可点击
  if (
    // limit.value - 1 > questionlist.value.length &&
    currQuestionIdx === questionlist.value.length - 1
  ) {
    return "F";
  }
  return false;
});

// routeQuery
const routeQuery = computed<{ order: string; offset: number; limit: number, teamid: string[], toSubmission: boolean }>(
  () => {
    return route.query as any;
  }
);
const order = computed(() => {
  return (routeQuery.value.order || "ID") as keyof Studycodemodel.Iquestion
});
const teamid = computed(() => {
  return routeQuery.value.teamid
})
// 题目列表 分页用
const offset = computed<number>({
  get() {
    return Number(routeQuery.value.offset) || 0
  },
  set(v) {
    router.push({
      query: { ...routeQuery.value, offset: v, },
    });
  },
});
const limit = computed<number>({
  get() {
    let defaultLimit = 20
    if (questionbankid.value || userId.value) {
      defaultLimit = questionlist.value.length
    }
    return Number(routeQuery.value.limit) || defaultLimit;
  },
  set(v) {
    router.push({
      query: { ...routeQuery.value, limit: v, },
    });
  },
});
// 下一题false、上一题true
async function goNext(x: boolean) {
  const currQuestionIdx = questionlist.value.findIndex((v) => v?.ID == ID.value);
  let id: number | undefined;
  let n = 0;
  // 如果是最后一个
  if (currQuestionIdx === limit.value - 1) {
    // 下一个 翻页
    if (!x) {
      await watchquestion(offset.value + limit.value);
      n = limit.value;
      await dealy(30);
      id = questionlist.value[0]?.ID;
    } else {
      id = questionlist.value[currQuestionIdx - 1]?.ID;
    }
  } else if (currQuestionIdx === 0) {
    if (!x) {
      id = questionlist.value[currQuestionIdx + 1]?.ID;
    } else {
      // 前一个
      await watchquestion(offset.value - limit.value);
      n = -Number(limit.value);
      await dealy(30);
      id = questionlist.value[limit.value - 1]?.ID;
    }
  } else {
    if (!x) {
      id = questionlist.value[currQuestionIdx + 1]?.ID;
    } else {
      id = questionlist.value[currQuestionIdx - 1]?.ID;
    }
  }
  // 
  if (!id) {
    id = questionlist.value[0]?.ID;
    if (!id) return;
  }
  const query = Object.assign(route.query, {
    offset: offset.value + n,
  });
  router.push({
    params: { ID: id },
    query: query,
  });
  // router.push({
  //   query: route.query,
  //   params: route.params
  // })
}
async function watchquestion(of?: number) {
  const obj: Iobj<Studycodemodel.Iquestion> = {
    _offset: of || offset.value,
    _limit: 20,
  }
  if (teamid.value && typeof Array.isArray(teamid.value)) {
    obj.teamid = store.state.team?.rows.filter(e => teamid.value.includes(e.ID ? String(e.ID) : '')).map(e => e.ID)
  }
  if (route.query.ID) {
    obj.ID = route.query.ID
  }
  if (route.query.name) {
    obj._like = ["name", route.query.name];
    const id = Number(route.query.name);
    if (id == Number(route.query.name)) {
      obj._like = ["ID", id];
    }
  }
  if (route.query.range) {
    obj.range = route.query.range
  } else {
    obj.name = 'public'
  }
  if (route.query.jobid) {
    (obj as any).jobid = route.query.jobid
  }
  if (route.query.activityid) {
    (obj as any).activityid = route.query.activityid
  }
  // 专题是单独接口获取题目列表
  if (!questionbankid.value) {
    await store.dispatch("actionquestion", obj);
  }
}

onMounted(() => {
  // 修改后（结合用户ID和题目ID）
  const userID = getuser.value.ID; // 假设getuser是当前用户信息
  const cacheKey = `${userID}-${ID.value}`;
  // 读取缓存
  const value = localStorage.getItem(cacheKey);
  if (value) {
    context.value = value
  }
  // 获取tabs选项卡权限
  getPermissionsCfg()
  // 确保 zrUp 已初始化
  if (zrUp.value) {
    zrUp.value.addEventListener('mousedown', (event) => {
      // 记录鼠标点击时的偏移量
      initialMouseOffset = event.clientY - bottom.value
      console.log('mousedown', event.clientY, bottom.value, initialMouseOffset,)
    })
  }
  // tabs切换
  if (routeQuery.value.toSubmission) {
    activeName.value = Tabs.MYSUBMISSION
  }
  // 
  fetchCounts();
});

watch(() => prop.question, ({ ID }) => {
  if (!ID) {
    router.push({ name: "题库", query: route.query });
    ElMessage.error("没有找到此题目");
  } else {
    start()
    // CF 没有底部测试
    // monacoHeight.value = "100%"
    fetchCounts();
  }
});

// watch(() => route.query, (v, old) => {
//   const n = difference(Object.values(v), Object.values(old))
// });

watch(() => ID.value, (_v, ol) => {
  const userID = getuser.value.ID;
  const oldCacheKey = `${userID}-${ol}`;
  const newCacheKey = `${userID}-${_v}`;

  // 保存旧题目的代码
  if (context.value) {
    localStorage.setItem(oldCacheKey, context.value);
  }
  if (!_v) return;
  // 加载新题目的代码
  context.value = localStorage.getItem(newCacheKey) || "";
}
);

watch(() => loading.value, (v) => {
  if (v) {
    consoleQuestionRef.value.consoleQuestionRef = "second";
  }
});

async function start() { }

async function runcode(run?: boolean) {
  isSub.value = false;
  _runcode();
  if (!context.value || context.value?.length < 20) {
    ElMessage.error("代码内容太少");
    return;
  }

  if (!ID.value) {
    ElMessage.error("没有登录");
    return;
  }

  if (!store.state.user) {
    ElMessage.error("没有登录");
    return;
  }

  if (!run && !textarea.value) {
    ElMessage.error("请填入测试用例");
    drawer.value = true;
    return;
  }
  // run true:为提交代码 false:运行测试
  run ? (loading.value = true) : (runTestLoading.value = true)
  const scoket: Socket | undefined =
    store.state.socket;
  if (scoket) {
    if (isCf.value) {
      // if (!getuser.value?.codeforcesoption?.handle) {
      //   codeforcesref.value.login()
      //   loading.value = false
      //   return
      // }
      scoket.emit("runcodeforces", {
        context: context.value,
        language: language2.value,
        textarea: textarea.value,
        questionid: Number(ID.value),
        questionbankid: questionbankid.value,
        userid: getuser.value.ID,
        run,
      });
    } else {
      scoket.emit("runcode", {
        context: context.value,
        language: language.value,
        textarea: textarea.value,
        questionid: Number(ID.value),
        questionbankid: questionbankid.value,
        userid: getuser.value.ID,
        run,
        gccoptimize: gccoptimize.value ? '-O2' : undefined,
        isfile: isfile.value,
      });
    }
    const arr: [string, any][] = [];

    arr[0] = ["_method_", "runcode"];
    arr[1] = ["type", "scoket"];
    arr[2] = ["questionid", String(ID.value)];
    arr[3] = ["questionname", String(prop.question.name)];
    arr[4] = ["ismatch", false];
    jilurizhi(arr);
  }
}

// 有问题？？？？？？
function change(v?: string, e?: monaco.editor.IModelContentChangedEvent) {
  if (e) {
    context.value = v ? v : '';
  }
}
function changePage(r: number) {
  offset.value = (r - 1) * limit.value;
}

watch(() => getcode?.value, (d) => {
  if (d) {
    const { data, run, error, msg = "" } = d;
    if (error) {
      ElMessage.error(msg);
      ouput.stdout = "";
      ouput.t = NaN;
      ouput.stderr = msg;
      if (!run) {
        isSub.value = true;
        router.push({
          name: '我的提交',
          query: route.query,
          params: route.params
        }).then(e => {

        })
      }
    } else {
      ElMessage.success("运行成功");
      if (run && data) {
        Object.assign(ouput, data[0]);
      } else {
        isSub.value = true;
        router.push({
          name: '我的提交',
          query: route.query,
          params: route.params
        })
      }
    }
    // 提交之后跳转我的提交 ??
    if (runTestLoading.value) {
      runTestLoading.value = false;
    } else {
      activeName.value = Tabs.MYSUBMISSION
      loading.value = false;
    }
  }
}
);

onBeforeRouteLeave(() => {
  const userID = getuser.value.ID;
  const cacheKey = `${userID}-${route.params.ID}`;
  if (context.value) {
    localStorage.setItem(cacheKey, context.value);
  }
});

const isCf = computed(() => {
  return prop.question.range === 'codeforces'
})
const showUserSolution = computed(() => {
  return (isAdmin.value || routerNames.value.find(e => e === '题目题解'))
  return (isAdmin.value)
})

// .zrUp margin-top: 20px;  margin-right: 20px;
let limitDis = 20
// 纵向拖拽自适应宽度
const zrUp = ref<HTMLDivElement>()
const monacoEl = ref<HTMLDivElement>()
const { top, right: monacoElRight, bottom } = useElementBounding(monacoEl)
const { y } = useMouse()
const mousePressed = useMousePressed({ target: zrUp, touch: false })
// 用来存储拖拽后的高度
const draggedHeight = ref('75%')
// 初始化变量
let initialMouseOffset = 0 // 鼠标点击时到 monaco-container 顶部的偏移量
// 临界值与收缩高度
const minHeightForConsole = 100;
const collapsedHeightForConsole = 40;
const windowHeight = ref(window.innerHeight);
// 是否启用平滑过渡
const isTransitionEnabled = ref(false);
// 鼠标距离底部 当前鼠标 y 位置到窗口底部的距离
const mouseBottomDistance = computed(() => {
  return windowHeight.value - y.value;
});
// 动态计算 ConsoleQuestion 的高度
const consoleHeight = computed(() => {
  if (mousePressed.pressed.value) {
    // 拖拽中，关闭过渡效果
    document.body.classList.add('disable-select'); // 禁用文字选择
    isTransitionEnabled.value = false;
    // 拖拽时动态计算高度
    const distance = mouseBottomDistance.value;
    return distance < minHeightForConsole
      ? `${collapsedHeightForConsole}px`
      : `${distance}px`;
  } else {
    // 拖拽结束后，启用过渡效果
    document.body.classList.remove('disable-select'); // 恢复文字选择
    isTransitionEnabled.value = true;
    // 非拖拽时返回拖拽结束后的高度
    return `${draggedHeight.value}px`;
  }
});

// 计算编辑器高度
const monacoHeight = computed(() => {
  if (!isCf.value && mousePressed.pressed.value) {
    const newHeight = y.value - top.value - initialMouseOffset
    return newHeight > 0 ? `${newHeight}px` : '0px'
  } else {
    // draggedHeight 会根据 watch(y.value) 来更新
    console.log("draggedHeight", draggedHeight.value)
    return isCf.value ? '100%' : draggedHeight.value
  }
})
// 监控 y 轴变化来实时更新拖拽后的高度
watch([y, mousePressed.pressed], ([newY, pressed]) => {
  // 判断 showCaseDetail.value 避免点击我的提交时触发拖拽而计算高度
  if (!showCaseDetail.value && !isCf.value && pressed) {
    const newHeight = newY - top.value - initialMouseOffset
    draggedHeight.value = newHeight > 0 ? `${newHeight}px` : '0px'
    // console.log("watch y", draggedHeight.value)
  }
})

// 横向拖拽自适应宽度
const asidewidth = ref('40%')
const zrleft = ref<HTMLDivElement>()
const aside = ref<HTMLDivElement>()
const showCaseDetailEl = ref<HTMLDivElement>()
const { left, } = useElementBounding(aside)
const { x } = useMouse()
const { pressed } = useMousePressed({ target: zrleft, touch: false })
watch(() => x.value, e => {
  let dis = e
  let right = monacoElRight.value
  // 判断右侧节点是 编辑器 还是 测评记录
  if (showCaseDetail.value) {
    const { top, right: showCaseDetailElRight, bottom } = useElementBounding(showCaseDetailEl)
    right = showCaseDetailElRight.value
  }
  dis = dis > (right - limitDis) ? (right - limitDis) : dis
  if (pressed.value) {
    document.body.classList.add('disable-select'); // 禁用文字选择
    // margin-right: 20px;
    let w = (dis - left.value - limitDis / 2)
    w = w > 0 ? w : limitDis
    asidewidth.value = w + 'px'
    // console.log("watch x",  asidewidth.value)
  } else {
    document.body.classList.remove('disable-select'); // 恢复文字选择
  }
})

// 各个tab中数据总数
const hiddenBadge = ref(true)
const submissionCount = ref(0)
const discussCount = ref(0)
const solutionCount = ref(0)
const ideaTipsCount = ref(0)
// 获取提交次数
async function fetchSubmissionCount() {
  const { count } = await asyncselectuserquestion({ questionid: ID.value, userid: getuser.value.ID, _offset: 0, _limit: 1, })
  submissionCount.value = count || 0
}
// 获取讨论次数
async function fetchDiscussCount() {
  const { count } = await asyncgetfabulouscomment({ ID: ID.value, _limit: 1, _offset: 0, state: [1, 2] });
  discussCount.value = count || 0
}
// 获取题解次数
async function fetchSolutionCount() {
  const { count } = await asyncselectusersolution({ questionid: ID.value, state: 1, _limit: 1, _offset: 0, })
  solutionCount.value = count || 0
}
// 获取AI思路次数
async function fetchIdeaTipsCount() {
  const { count } = await asyncUserSelectacaicontent({ questionid: ID.value, _limit: 1, })
  ideaTipsCount.value = count || 0
}
// 初始化一起请求
async function fetchCounts() {
  await Promise.all([fetchSubmissionCount(), fetchDiscussCount(), fetchSolutionCount(), fetchIdeaTipsCount(),])
}
// tab切换监听，按需请求
watch(() => activeName.value, (newTab) => {
  if (newTab === Tabs.MYSUBMISSION) {
    fetchSubmissionCount()
  } else if (newTab === Tabs.QUESTIONDISCUSS) {
    fetchDiscussCount()
  } else if (newTab === Tabs.QUESTIONSOLUTION) {
    fetchSolutionCount()
  } else if (newTab === Tabs.AIIDEATIPS) {
    fetchIdeaTipsCount()
  }
})

const getCurrentDateFormatted = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = (today.getMonth() + 1).toString().padStart(2, '0');
  const day = today.getDate().toString().padStart(2, '0');
  return `${year}-${month}-${day}`;
};

const chatContextString = computed(() => {
  const pageName = "题目练习页面";
  const problemId = ID.value || 'N/A';
  const currentDate = getCurrentDateFormatted();
  const myCode = context.value || '';
  return `日期:${currentDate},当前所在页面:${pageName},当前练习题目ID:${problemId},我的代码:${myCode}`;
});

const showAIChat = computed(() => {
  console.log("showAIChat", isHGKJteam.value, teamId.value, (isHGKJteam.value || teamId.value == 2128))
  return (isHGKJteam.value || teamId.value == 2128)
})

</script>

<style scoped>
#question {
  height: 100%;
  padding: var(--container-margin) 5% 0;
  margin: var(--container-margin) 0rem 0 0rem;
  /* 外边距 */
  --container-margin: 20px;
  --container-header-height: 20vh;
  --container-bg-color: #fff;
  --monaco-header: 60px;

  overflow: hidden;
}

#question.btn-outline-primary:hover {
  background-color: #409eff;
}

.container-content {
  overflow-y: auto;
  overflow-x: hidden;
  background-color: var(--container-bg-color);
  margin-right: calc(var(--container-margin) * 0.75);
  position: relative;
  padding: 0;
  min-width: var(--container-margin);
}

.foter {
  /* padding: 0 calc(var(--container-margin)/2); */
  /* height: 46px; */
  /* line-height: 46px; */

  /* 宽度撑满剩余-flex控制靠右和居中 */
  /* z-index: 99; */
  /* background-color: rgba(244, 248, 255, 1); */
  width: 100%;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  /* position: absolute;
  right: 0;
  top: 0; */
}

.question-chg-page-btn-box {
  /* width: 202px; */
  display: inline-block;
}

/* 翻页按钮 */
.question-chg-page-btn {
  width: 75px;
  height: 32px;
  border-radius: 4px;
  border: 1px solid rgba(70, 131, 250, 1);
}

.question-question-list-btn {
  margin-left: calc(var(--container-margin)/2);
  border-radius: 4px;
  border: 1px solid rgba(70, 131, 250, 1);
}

/* 左侧tabs的内容 */
.tab-container {
  padding: 2px;
  /* nav-header height:64px  选项卡Tabs height:50px*/
  height: calc(100vh - 64px - var(--el-tabs-item-height) - var(--container-margin)*2);
}

/* 右侧分为上下 */
.container-right-box {
  height: calc(100vh - 64px - var(--container-margin)*2);
  min-width: var(--container-margin);
}

.container-box-shadow {
  border-radius: var(--container-border-radius);
  box-shadow: var(--container-box-shadow);
}

.submission-container-right {
  height: calc(100vh - 64px - var(--container-margin)*2);
  background-color: #fff;
  /*  */
  border-radius: var(--container-border-radius);
  box-shadow: var(--container-box-shadow);
}

/* 右侧上 */
.monaco-container-box {
  height: 100%;
  display: flex;
  flex-direction: column;

  overflow: hidden;
  border-radius: var(--container-border-radius) !important;
}

.monaco-container {
  background: var(--container-bg-color);
  height: 70%;
  min-height: var(--monaco-header);
}

.monaco-header {
  height: var(--monaco-header);
  padding: 10px;
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

#monaco {
  /* header height 62px */
  height: calc(100% - 62px - var(--container-border-radius));
  overflow: hidden;
}

.headers {
  /* overflow: hidden;
  line-height: 45px; */
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.code-submit-btn,
.code-AI-btn {
  width: 100px;
  height: 36px;
  border-radius: 4px;
}

.code-AI-btn {
  /* width: 90px; */
}

.code-submit-btn {
  background-color: rgba(70, 131, 250, 1);
}

/*  */
.console-question {
  border-top: 1px solid #dcdfe6;
  overflow: hidden;
  /* 默认无平滑过渡 */
  transition: none;
}

/* 拖拽结束后启用平滑过渡 */
.console-question.transition-enabled {
  transition: height 1s ease;
}
</style>

<style>
#question .el-tabs__header,
#question .el-tabs--border-card>.el-tabs__content {
  padding: 0;
}

.drawer .el-tabs__content {
  margin: 5px;
  overflow-y: auto;
}

#question button:focus {
  outline: none;
}

#question {
  /* flex-shrink: inherit */
}

/* 使得tabs头部选项卡宽度撑满父容器 */
#question .el-tabs__nav {
  /* position: static;
  float: none; */
}

/* 编辑器去掉 预览图后左侧有边框 */
#question .slider-mouseover {
  border-left: none;
}

#question .el-badge__content--primary {
  /* height: 20px;
  width: 20px; */
  /* border-radius: 50% !important; */
  /* border-color: rgba(70, 131, 250, 1); */
  /* background-color: var(--el-button-bg-color); */
  /* color: rgba(70, 131, 250, 1); */
}
</style>